<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 1.手撕map
    Array.prototype.myMap = function (arr, cb) {
      if (!Array.isArray(arr) || arr.length === 0 || typeof cb !== 'function') {
        return []
      } else {
        let res = []

        for (let i = 0; i < arr.length; i++) {
          res.push(cb(arr[i], i, arr))
        }
        return res
      }

    }

    // 2.手撕filter
    Array.prototype.myFilter = function (arr, cb) {
      // 1.检查参数是否符合要求
      if (!Array.isArray(arr) || !arr.length || typeof cb !== 'function') {
        return []
      } else {
        let res = []

        for (let i = 0; i < arr.length; i++) {
          if (cb(arr[i], i, arr)) {
            res.push(arr[i])
          }
        }
        return res
      }
    }

    // 3.手写reduce
    const myReduce = function (arr, cb, initial) {
      // 1.检查参数是否正常
      if (!Array.isArray(arr) || !arr.length || typeof cb !== 'function') {
        return []
      } else {
        let hasInitial = initial !== undefined
        let value = hasInitial ? initial : arr[0]
        let startIndex = hasInitial ? 0 : 1
        for (let i = startIndex; i < arr.length; i++) {
          value = cb(value, arr[i], i, arr)

        }
        return value
      }
    }

    // console.log(myReduce([1, 2, 3], (prev, item) => {
    //   return prev + item
    // }));
  </script>
</body>

</html>